package org.example.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;
import java.util.Properties;

@Slf4j
public class ESClientUtils {
    private static RestHighLevelClient client;
    private static final String PROPERTIES_PATH = "elasticsearch.properties";

    private ESClientUtils() {}

    public static synchronized RestHighLevelClient getClient() {
        if (client == null) {
            initClient();
        }
        return client;
    }

    private static void initClient() {
        try {
            Properties properties = ConfigLoader.loadProperties(PROPERTIES_PATH);
            String host = properties.getProperty("es.host");
            int port = Integer.parseInt(properties.getProperty("es.port"));
            String scheme = properties.getProperty("es.scheme");
            String username = properties.getProperty("es.username");
            String password = properties.getProperty("es.password");

            // 创建认证凭证
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));

            // 构建RestClientBuilder
            RestClientBuilder builder = RestClient.builder(
                    new HttpHost(host, port, scheme))
                    .setHttpClientConfigCallback(httpClientBuilder -> {
                        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        return httpClientBuilder;
                    });

            client = new RestHighLevelClient(builder);
            log.info("Elasticsearch client initialized successfully");
        } catch (Exception e) {
            log.error("Failed to initialize Elasticsearch client", e);
            throw new RuntimeException("Failed to initialize Elasticsearch client", e);
        }
    }

    public static synchronized void closeClient() {
        if (client != null) {
            try {
                client.close();
                client = null;
                log.info("Elasticsearch client closed successfully");
            } catch (IOException e) {
                log.error("Failed to close Elasticsearch client", e);
            }
        }
    }
}
